var $        = require('gulp-load-plugins')();
var gulp     = require('gulp');
var rimraf   = require('rimraf');
var sequence = require('run-sequence');
var sherpa   = require('style-sherpa');
var historyApiFallback = require('connect-history-api-fallback');

$.haml     = require('gulp-ruby-haml');
$.browser = require('browser-sync').create();
$.pngquant = require('imagemin-pngquant');
$.sh = require('shelljs');

// var panini   = require('panini');

var config = require("./gulp/config.js")();
var gulpTaskList = require("fs").readdirSync("./gulp/tasks/");

var argv     = require('yargs').argv;
// Check for --production flag
config.isProduction = !!(argv.production);

gulpTaskList.forEach( function(taskfile) {
  require("./gulp/tasks/" + taskfile)(gulp, $, config);
});

// Delete the "dist" folder
// This happens every time a build starts
gulp.task('clean', function(done) {
  rimraf('public', done);
});

gulp.task("check", function(done) {
  if (!$.sh.test('-e', 'coffee/services/config.coffee')){
    console.log('  ' + $.util.colors.red('copy config.coffee to config.'));
    $.sh.cp('coffee/services/config.coffee.sample', 'coffee/services/config.coffee');
  }

  done();
});

// Build the "dist" folder by running all of the above tasks
gulp.task('build', function(done) {
  sequence('clean', ['check', 'sass', 'haml', 'coffee', 'img', 'icomoon', 'lib',], 'replace-cdn', done);
});

// Start a server with LiveReload to preview the site in
gulp.task('serve', ['build'], function() {
  $.browser.init({
    server: {
      baseDir: 'public',
      middleware: [ historyApiFallback() ]
    },
    port: config.PORT
  });
  gulp.watch(config.sass.path, ['sass']);
  gulp.watch(config.haml.path, ['haml']);
  gulp.watch(config.coffee.path, ['coffee']);
  // gulp.watch(config.js.path, ['js']);
  gulp.watch(config.img.path, ['img']);
});

// Build the site, run the server, and watch for file changes
gulp.task('default', ['build'], function() {
});

gulp.task('watch', function() {
  gulp.watch(config.sass.path, ['sass']);
  gulp.watch(config.haml.path, ['haml']);
  gulp.watch(config.coffee.path, ['coffee']);
  // gulp.watch(config.js.path, ['js']);
  gulp.watch(config.img.path, ['img']);
});

gulp.task('publish', function() {
  $.sh.exec('rsync -avz --exclude=cordova.js -e "ssh -p12223" public/ root@www.juncaijinfu.com:/home/deploy/www_production/lps')
})

